import Vue from 'vue';
import Vuex from 'vuex';
import createLogger from 'vuex/dist/logger';
import cloneDeep from 'lodash/cloneDeep';
import modules from './modules';

Vue.use(Vuex);

const debug = process.env.NODE_ENV !== 'production';

const moduleState = {};
(function globalDefaultState() {
  if (!modules || Object.keys(modules).length === 0) return moduleState;
  Object.keys(modules).forEach(key => {
    moduleState[key] = cloneDeep(modules[key].state);
  });
})();

export default new Vuex.Store({
  mutations: {
    // 重置全局 state 状态
    RESET_GLOBAL_STORE(state, payload) {
      // 清除缓存中的用户登录信息
      window.localStorage.removeItem('auth.currentUser');
      Object.assign(state, {
        ...cloneDeep(moduleState),
        user: payload || { currentUser: {} },
      });
    },
  },
  actions: {
    resetGlobalState({ commit }, payload) {
      commit('RESET_GLOBAL_STORE', payload);
    },
  },
  modules,
  strict: debug,
  plugins: debug ? [createLogger()] : [],
});
